package com.pets.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pets.ViewModels.MyCourseViewModels;
import com.pets.mapper.CourseManagementMapper;
import com.pets.mapper.UsersMapper;
import com.pets.pojo.CourseManagement;
import com.pets.pojo.MyCourse;
import com.pets.mapper.MyCourseMapper;
import com.pets.pojo.Users;
import com.pets.service.IMyCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pets.utils.Result;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 我的课程 服务实现类
 * </p>
 *
 * @author 小陳同學
 * @since 2024-05-14
 */
@Service
public class MyCourseServiceImpl extends ServiceImpl<MyCourseMapper, MyCourse> implements IMyCourseService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private MyCourseMapper myCourseMapper;

    @Autowired
    private CourseManagementMapper courseManagementMapper;

    /**
     * 预约课程
     * @param myCourse
     * @return
     */
    @Override
    public Result register(MyCourse myCourse) {
        if(myCourse==null){
            return Result.fail("未获取到参数！");
        }
        if(myCourse.getCourseId()==null){
            return Result.fail("未获取到课程id值：CourseId！");
        }
        if(myCourse.getUserId()==null){
            return Result.fail("未获取到当前登陆人userId值！");
        }
        if(myCourse.getClassTime()==null){
            return Result.fail("未获取到预约时间ClassTime值！");
        }
        //根据课程id与登陆人id与时间判断是否预约过
        LambdaQueryWrapper<MyCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MyCourse::getUserId, myCourse.getUserId())
                .ge(MyCourse::getClassTime, myCourse.getClassTime().toLocalDate())
                .lt(MyCourse::getClassTime, myCourse.getClassTime().toLocalDate().plusDays(1));
        List<MyCourse> financialManagementList = myCourseMapper.selectList(queryWrapper);
        if(myCourseMapper.selectCount(queryWrapper)>0){
            return Result.fail("你已经预约过了！");
        }
        //判断课程是否存在
        CourseManagement courseManagement = courseManagementMapper.selectById(myCourse.getCourseId());
        if(courseManagement==null){
            return Result.fail("课程不存在！");
        }
        //判断当前登陆人类型，并判断是否有足够会员卡次数
        Users users = usersMapper.selectById(myCourse.getUserId());
        if(users==null){
            return Result.fail("未查询到用户！");
        }
        if(courseManagement.getConsumptionFrequency()!=null&&courseManagement.getConsumptionFrequency()>0){
            if(users.getVipNumber()==null||courseManagement.getConsumptionFrequency()>users.getVipNumber()){
                return Result.fail("健身房次卡不足，请充值！");
            }
            //更新用户
            users.setVipNumber(users.getVipNumber() - courseManagement.getConsumptionFrequency());//减少会员卡
            usersMapper.updateById(users);
            myCourse.setConsumptionFrequency(courseManagement.getConsumptionFrequency());
        }else {
            myCourse.setConsumptionFrequency(0);
        }
        return myCourseMapper.insert(myCourse) > 0 ? Result.success("成功") : Result.fail("失败");
    }

    /**
     * 取消预约课程
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Integer id) {
        //判断当前课程时间是否小于等于当前时间
        MyCourse myCourse = myCourseMapper.selectById(id);
        if(myCourse==null){
            return Result.fail("未查询到预约课程！");
        }
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        LocalDateTime classTime = myCourse.getClassTime(); // 假设这个方法返回LocalDateTime
        if (!classTime.toLocalDate().isAfter(currentDate)) {
            //是，不能取消
            return Result.fail("预约课程在今天或是过去，不能取消！");
        }
        //不是，取消，并退还会员次数
        Users users = usersMapper.selectById(myCourse.getUserId());
        if(users==null){
            return Result.fail("未查询到预约用户！");
        }
        Integer vipNumber = users.getVipNumber();
        Integer consumptionFrequency = myCourse.getConsumptionFrequency();
        vipNumber+=consumptionFrequency;
        if(usersMapper.updateById(users)<=0){
            return Result.fail("取消失败！");
        }
        int rows = myCourseMapper.deleteById(id);
        return rows > 0 ? Result.success("取消成功") : Result.error("取消失败");
    }


    @Override
    public Result selectPage(Integer page, Integer pageSize, Integer userId) {
        //查询集合
        final LambdaQueryWrapper<MyCourse> lqw = new LambdaQueryWrapper<>();
        lqw.eq(userId != null, MyCourse::getUserId, userId);
        IPage<MyCourse> Page = new Page<>(page, pageSize);
        IPage<MyCourse> IPage = myCourseMapper.selectPage(Page, lqw);

        //返回模型
        List<MyCourseViewModels> myCourseViewModels = new ArrayList<>();
        IPage<MyCourseViewModels> newIPage = new Page<>();
        newIPage.setPages(IPage.getPages());
        newIPage.setCurrent(IPage.getCurrent());
        newIPage.setSize(IPage.getSize());
        newIPage.setTotal(IPage.getTotal());

        //判断是否返回
        List<MyCourse> myCourseList = IPage.getRecords();
        if(myCourseList==null||myCourseList.size()<=0){
            newIPage.setRecords(myCourseViewModels);
            return Result.success("查询成功！",newIPage);
        }

        //对象映射器
        ModelMapper modelMapper = new ModelMapper();
        for (MyCourse myCourse : myCourseList) {
            MyCourseViewModels myCourseVM = modelMapper.map(myCourse, MyCourseViewModels.class);
            if(myCourseVM.getCourseId()!=null){
                CourseManagement courseManagement = courseManagementMapper.selectById(myCourseVM.getCourseId());
                if(courseManagement!=null){
                    myCourseVM.setCourseName(courseManagement.getCourseName());
                }
            }
            myCourseViewModels.add(myCourseVM);
        }
        // 使用Stream API和sorted方法进行降序排序
        List<MyCourseViewModels> sortedEntities = myCourseViewModels.stream()
                .sorted(Comparator.comparing(MyCourseViewModels::getClassTime).reversed())
                .collect(Collectors.toList());
        newIPage.setRecords(sortedEntities);
        return Result.success("查询成功", newIPage);
    }

}
